import requests
import json
from pyquery import PyQuery as pq


def getMoiveListByUrl(url):
    """
    由一个分页链接开始，通dom节点的形式 + 数据处理(正则处理、字符处理、类型转换等)， 获取电影信息
    :return: list: 包含每部电影详细信息的字典组成的列表。
    """
    # 定义请求头
    headers = {

        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        # 其他需要的请求头...
    }
    movieList = []
    # 发送 GET 请求并获取响应内容
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        # todo pyquery 解析dom，经过循环，数据处理(正则处理、字符处理、类型转换等)，得到正确的电影属性信息
        doc = pq(response.text)
        movie_list_doc = doc("#content .grid_view .item")
        for item in movie_list_doc.items():
            item_dict = {

            }  # 存储单个电影对象的字典
            cover = item('.pic img').attr('src')
            movie_url = item('.pic a').attr('href')
            title = item('.info .hd .title:first').text()
            review_count_text = item('.info .bd .star span:contains("人评价")').text()
            rating_num = item('.info .bd .star .rating_num').text()
            review_count = int(review_count_text.replace("人评价", ""))
            item_dict['title'] = title
            item_dict['cover'] = cover
            item_dict['review_count'] = review_count
            item_dict['rating_num'] = rating_num
            item_dict['movie_url'] = movie_url
            # print(title)
            movieList.append(item_dict)

        return movieList
    else:
        return movieList


if __name__ == "__main__":
    pageUrl02 = 'https://movie.douban.com/top250?start=25&filter='
    movieList = getMoiveListByUrl(pageUrl02)
    print(movieList)
